package cn.samir.sudoku.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.view.View;
import cn.samir.sudoku.R;
import cn.samir.sudoku.core.Sudokus;
import cn.samir.sudoku.db.dao.SudokuDao;
import cn.samir.sudoku.keys.Conf;
import cn.samir.sudoku.net.NetTask;
import cn.samir.sudoku.net.NetWorkHelper;
import cn.samir.sudoku.net.OnNetListener;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.PlatformDb;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.tencent.qq.QQ;

public class Utils {
	public final static String isHelpButtonEnabled = "isHelpButtonEnabled";
	public static final int NOT_SET = 0;
	public static final boolean ENABLE = true;
	public static final boolean DISABLE = false;
	public static final String Header_40 = "icon40_";
	public static final String Header_100 = "icon100_";
	public static final String sharepreference_name = "sudokus_info";
	public static boolean isNumberLegal(int number) {
		if (number > 0 && number < 10) {
			return true;
		}
		return false;
	}

	@SuppressWarnings("unchecked")
	public static <T> T getView(Activity act, int id) {
		return (T) act.findViewById(id);

	}

	@SuppressWarnings("unchecked")
	public static <T> T getView(View act, int id) {
		return (T) act.findViewById(id);

	}

	public static String generateString() {
		String ready = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		StringBuilder sb = new StringBuilder();
		int size = ready.length();
		Random random = new Random();
		for (int i = 0; i < 32; i++) {
			sb.append(ready.charAt(random.nextInt(size)));
		}
		return sb.toString();
	}

	public static int getSharePreInt(Context c, String name) {
		return c.getSharedPreferences(sharepreference_name, Context.MODE_PRIVATE).getInt(
				name, 0);
	}

	public static String getSharePreString(Context c, String name) {
		return c.getSharedPreferences(sharepreference_name, Context.MODE_PRIVATE)
				.getString(name, null);

		// return PreferenceManager.getDefaultSharedPreferences(c).getBoolean(
		// isHelpButtonEnabled, false);
	}

	public static boolean putSharedPre(Context c, String name, String value) {
		return c.getSharedPreferences(sharepreference_name, Context.MODE_PRIVATE).edit()
				.putString(name, value).commit();
	}

	public static void login(Activity act, PlatformActionListener listener,
			String platname) {
		ShareSDK.initSDK(act);
		Platform platform = ShareSDK.getPlatform(platname);
		platform.SSOSetting(false);
		platform.setPlatformActionListener(listener);
		platform.authorize();
	}

	public static void info(Context context, HashMap<String, String> params,
			OnNetListener listener) {
		NetTask netTask = new NetTask(context);
		netTask.url(Conf.info_url).addParams(params).doGet(listener);
	}

	public static void netFile(final String url, final String filename) {

		ThreadPoolManager.getInstance().addTask(new Runnable() {

			@Override
			public void run() {
				InputStream in;
				String filepath = Conf.file_root;
				String name = filename;

				FileOutputStream fos = null;
				File file = new File(filepath, name);
				try {
					in = NetTask.syncStream(url, "GET", null);

					if (file.exists() && file.canExecute()) {
						file.delete();
						return;
					}
					fos = new FileOutputStream(file);
					byte[] b = new byte[1024];
					int len = 0;
					while ((len = in.read(b)) > 0) {
						fos.write(b, 0, len);
					}
					fos.flush();
				} catch (Exception e) {
					if (!file.delete()) {
						file.deleteOnExit();
					}
					e.printStackTrace();
				} finally {
					if (fos != null) {
						try {
							fos.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}
		});

	}

	public static void onekeyshare(Context context,
			HashMap<String, String> params) {
		ShareSDK.initSDK(context);
		OnekeyShare oks = new OnekeyShare();
		// oks.setTheme(OnekeyShareTheme.SKYBLUE);

		// 关闭sso授权
		oks.disableSSOWhenAuthorize();
		oks.setDialogMode();
		// 分享时Notification的图标和文字 2.5.9以后的版本不调用此方法
		// oks.setNotification(R.drawable.ic_launcher,
		// getString(R.string.app_name));
		// title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
		for (int i = 0; i < params.size(); i++) {

			if (params.containsKey("title")) {
				oks.setTitle(params.get("title"));
			} else {
				oks.setTitle("推荐一个耐玩的游戏!");
			}

			if (params.containsKey("titleurl")) {
				oks.setTitleUrl(params.get("titleurl"));
			} else {
				// titleUrl是标题的网络链接，仅在人人网和QQ空间使用
				oks.setTitleUrl(Conf.apkUrl);
			}

			if (params.containsKey("text")) {
				// text是分享文本，所有平台都需要这个字段
				oks.setText(params.get("text"));
			} else {
				// text是分享文本，所有平台都需要这个字段
				oks.setText("发现一个好玩的游戏，脑子不够用啊~");
			}
			if (params.containsKey("imagePath")) {
				oks.setImageUrl(params.get("imagePath"));
			} else {
				// imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
				Bitmap bitmap = BitmapFactory.decodeResource(
						context.getResources(), R.drawable.ic_launcher);
				OutputStream stream = null;
				File file = null;
				try {
					file = new File(Conf.file_root, "ic_logo.png");
					if (file.exists()) {

					} else {
						stream = new FileOutputStream(file);
						bitmap.compress(CompressFormat.PNG, 80, stream);

					}
					oks.setImagePath(file.getAbsolutePath());// 确保SDcard下面存在此张图片
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				// oks.setImageUrl("http://sudokus.sinaapp.com/logo_96.png");
			}
		}
		// url仅在微信（包括好友和朋友圈）中使用
		oks.setUrl(Conf.apkUrl);

		// comment是我对这条分享的评论，仅在人人网和QQ空间使用
		oks.setComment("好玩");
		// site是分享此内容的网站名称，仅在QQ空间使用
		oks.setSite(context.getString(R.string.app_name));
		// siteUrl是分享此内容的网站地址，仅在QQ空间使用
		oks.setSiteUrl(Conf.apkUrl);

		// 启动分享GUI
		oks.show(context);
	}

	public static String formatSeconds(int seconds) {
		if (seconds < 0) {
			return "00:00";
		} else if (seconds < 60) {
			return "00:" + seconds;
		} else if (seconds < 3600) {
			return seconds / 60 + ":" + seconds % 60;
		} else {
			return seconds / 3600 + ":" + ((seconds % 3600) / 60) + ":"
					+ seconds % 60;
		}
	}

	public static boolean getConfig(Context context, String name) {
		// return context.getSharedPreferences("soduku", Context.MODE_PRIVATE)
		// .getInt(name, NOT_SET);
		return PreferenceManager.getDefaultSharedPreferences(context)
				.getBoolean(isHelpButtonEnabled, false);
	}

	/**
	 * public int passed = 0;// 是否通过 0/1 public int numberHelp;// 不是0的个数 public
	 * int sudokuid;// id 7位数字 public String content;// 初盘 public String
	 * pauseContent;// 暂时保存 public String fullContent;// 终盘 public String
	 * description;// 描述 public int score;// 分数
	 * 
	 * @param sudokus
	 * @param context
	 */
	public static void uploadSudokuSuccessToServer(Sudokus sudokus,
			Context context) {
		NetTask netTask = new NetTask(context);
		HashMap<String, String> param = new HashMap<String, String>();
		param.put("requestcode", "10003");
		String code = getSharePreString(context, "code");
		if (code == null) {
			return;
		}
		param.put("vtp", md5(code));
		param.put("username", getUserId(context));
		param.put("sudokuid", sudokus.sudokuid + "");
		param.put("time", sudokus.time + "");
		param.put("fullContent", sudokus.fullContent + "");
		// param.put("description", sudokus.description + "");
		param.put("score", sudokus.score + "");
		netTask.url(Conf.info_url).addParams(param).doGet(new OnNetListener() {

			@Override
			public void onSuccess(InputStream in) {

			}

			@Override
			public void onSuccess(String result) {
				LogUtils.d("Utils", result);

			}

			@Override
			public void onError(String result) {

			}
		});
	}

	public static String md5(String s) {
		try {
			// Create MD5 Hash
			MessageDigest digest = java.security.MessageDigest
					.getInstance("MD5");
			digest.update(s.getBytes());
			byte messageDigest[] = digest.digest();

			return toHexString(messageDigest);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}

		return "";
	}

	private static final char HEX_DIGITS[] = { '0', '1', '2', '3', '4', '5',
			'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
	public static String toHexString(byte[] b) { // String to byte
		StringBuilder sb = new StringBuilder(b.length * 2);
		for (int i = 0; i < b.length; i++) {
			sb.append(HEX_DIGITS[(b[i] & 0xf0) >>> 4]);
			sb.append(HEX_DIGITS[b[i] & 0x0f]);
		}
		return sb.toString();
	}

	public static void getHistoryFromServer(final Context context,
			final Handler handler) {

		if (!NetWorkHelper.isNetworkAvailable(context)) {
			handler.sendEmptyMessage(16);
			return;
		}
		NetTask netTask = new NetTask(context);
		HashMap<String, String> param = new HashMap<String, String>();
		param.put("username", Utils.getUserId(context));
		final String code = Utils.getSharePreString(context, "code");
		param.put("vtp", Utils.md5(code));
		param.put("requestcode", 10004 + "");
		netTask.url(Conf.info_url).addParams(param).doGet(new OnNetListener() {

			@Override
			public void onSuccess(InputStream in) {

			}

			/**
			 * 03-30 15:22:49.154: I/ui.UserHistoryActivity(10657):
			 * ﻿{"status":1,"data": [{"fullcontent":
			 * "345697182628431579791528346584916237273845961916273458432789615859164723167352894"
			 * , "id":"21","content":
			 * "305607102000431000700508006584000237070000060916000458400709005000164000107302804"
			 * , "score":"30","description":"no more to say","marks":"ok",
			 * "sudokuid":"1000044"}, {"fullcontent":
			 * "429251867857926413136784259943862175275193648681475392594638721768219534312547986"
			 * , "id":"20","content":
			 * "429251867857926413136784259943862175275193648681475392594638721768219534312547980"
			 * , "score":"30","description":"no more to say","marks":"ok",
			 * "sudokuid":"1000061"}]}
			 */
			@Override
			public void onSuccess(String result) {

				if (!TextUtils.isEmpty(result)) {
					try {
						JSONObject jsonObject = new JSONObject(result);
						int status = jsonObject.getInt("status");
						if (status == 1) {
							String data = jsonObject.getString("data");
							JSONArray jsonArray = new JSONArray(data);
							int count = 0;
							if (jsonArray != null && jsonArray.length() > 0) {
								count = jsonArray.length();
							}

							for (int i = 0; i < count; i++) {
								JSONObject object = jsonArray.getJSONObject(i);
								Sudokus sudokus = new Sudokus();
								sudokus.content = object.getString("content");
								sudokus.description = object
										.getString("description");
								sudokus.score = object.getInt("score");
								sudokus.sudokuid = object.getInt("sudokuid");
								sudokus.fullContent = object
										.getString("fullcontent");
								sudokus.sid = object.getInt("id");
								LogUtils.i(result, sudokus.toString());
								sudokus.passed = 1;
								sudokus.code = code;
								SudokuDao dao = new SudokuDao(context);
								if (dao.query(sudokus.content) == null) {
									dao.insert(sudokus);
								} else {
									dao.update(sudokus);
								}
							}
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}

				handler.sendEmptyMessage(16);

			}

			@Override
			public void onError(String result) {

			}
		});
		;
	}

	public static int getSocre(int score) {
		return (score - 30) * (score - 30) + 300;
	}

	public static int getUserAllScore(Context context) {

		SudokuDao dao = new SudokuDao(context);
		String code = getSharePreString(context, "code");
		ArrayList<Sudokus> s = dao.queryPassed(code);
		int score = 0;
		for (Sudokus sudokus : s) {
			score += getSocre(sudokus.score);
		}
		return score;
	}

	public static String getUserName(Context context) {
		return getSharePreString(context, "nickname");
	}

	public static String getUserIcon(Context context) {
		return getSharePreString(context, "userIcon");
	}

	public static String getUserBigHeaderLocal(Context context) {
		return null;
	}

	public static String getUserBigHeaderUrl(Context context) {
		return getSharePreString(context, "figureurl_qq_2");
	}

	public static String getUserId(Context context) {

		return getSharePreString(context, "userid");
	}

	public static String getUserGender(Context context) {
		return getSharePreString(context, "gender");
	}

	/**
	 * Utils.putSharedPre(this, "figureurl_qq_2", figureurl_qq_2);
	 * Utils.putSharedPre(this, "userId", id); Utils.putSharedPre(this,
	 * "userIcon", userIcon); Utils.putSharedPre(this, "gender", gender);
	 * Utils.putSharedPre(this, "nickname", nickname);
	 * 
	 * @param context
	 * @return
	 */
	public static void setUserId(Context context, String id) {
		putSharedPre(context, "userid", id);
	}

	public static void setUserGender(Context context, String gender) {
		putSharedPre(context, "gender", gender);
	}

	public static void setUserName(Context context, String value) {
		putSharedPre(context, "nickname", value);
	}

	public static void setUserIcon(Context context, String value) {
		putSharedPre(context, "userIcon", value);
	}

	public static void setUserBigHeaderLocal(Context context, String value) {
		putSharedPre(context, "figureurl_qq_2", value);
	}

	public static void setUserBigHeaderUrl(Context context, String value) {
		putSharedPre(context, "figureurl_qq_2", value);
	}

	public static boolean isLogin(Context context) {
		return (getUserId(context) != null) && (getUserName(context) != null)
				&& (getUserIcon(context) != null)
				&& (null != getUserGender(context));
	}

	public static void loginOut(Context context) {
		context.getSharedPreferences(sharepreference_name, Context.MODE_PRIVATE).edit()
				.clear().commit();
	}

}
